package logic

import (
	"context"
	"edu/models/cache"
	"edu/models/mysql"
	"fmt"

	"edu/edurpc/edurpc"
	"edu/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *edurpc.ForgetPasswordRequest) (*edurpc.ForgetPasswordResponse, error) {
	smsCode, _ := cache.Rdb.Get(l.ctx, "smsCode_"+in.Account).Result()
	if in.SmsCode != smsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	var user mysql.User
	mysql.DB.Where("account = ?", in.Account).First(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在")
	}
	user.Password = in.Password
	mysql.DB.Updates(&user)
	return &edurpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
